package com.example.view.module.event.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;

/**
 * 事件分发小案例
 */
public class MyLinearLayout extends LinearLayout {

    public MyLinearLayout(Context context) {
        super(context);
    }

    public MyLinearLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * 拦截触摸事件
     *
     * @param ev
     * @return true：触发当前View的onTouchEvent,false:继续传递给孩子
     */
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return true;
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {

        int width = getWidth() / getChildCount();
        int height = getHeight();
        int count = getChildCount();

        float eventX = event.getX();

        if (eventX < width) {
            getChildAt(0).dispatchTouchEvent(event);
            return true;
        } else if (eventX > width && eventX < width * 2) {  //滑动中间的控件[ListView]
            float eventY = event.getY();
            if (eventY < height / 2) {
                for (int i = 0; i < getChildCount(); i++) {
                    getChildAt(i).dispatchTouchEvent(event);
                }
                return true;
            } else if (eventY > height / 2) {
                getChildAt(1).dispatchTouchEvent(event);
//                event.setLocation(width / 2, event.getY());
                return true;
            }
        } else if (eventX > width * 2) {
            getChildAt(2).dispatchTouchEvent(event);
            return true;
        }

        return true;
    }
}
